package com.sgy.netty.http;

import com.sgy.netty.chat.NettyChatServer;
import com.sgy.netty.chat.NettyChatServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyHttpServer {

    private int port;

    public NettyHttpServer(int port) {
        this.port = port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workerGroup = null;
        try {
            // 创建bossGroup线程组处理连接事件
            bossGroup = new NioEventLoopGroup(1);

            // 创建workGroup线程组处理读写事件
            workerGroup = new NioEventLoopGroup();

            // 创建服务端启动助手
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            // 设置bossGroup和workerGroup
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)  // 设置通道实现为nio
                    .option(ChannelOption.SO_BACKLOG, 128)  // 设置参数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)  // 设置通道活跃状态
                    .childHandler(new ChannelInitializer<Channel>() {  // 创建通道初始化对象
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            // 添加编解码器
                            channel.pipeline().addLast(new HttpServerCodec());

                            // 添加自定义业务处理器
                            channel.pipeline().addLast(new NettyHttpServerHandler());
                        }
                    });

            // 启动服务端并绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(port);  // 异步处理
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("端口绑定成功...");
                    } else {
                        System.out.println("端口绑定失败...");
                    }
                }
            });
            System.out.println("http服务端启动成功...");

            // 关闭通道（不是真正意义的关闭，而是监听通道关闭状态）和关闭连接池
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyHttpServer(8080).run();
    }
}
